/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gae.client;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.TextBox;

/**
 * This class represents a text box in which only doubles are allowed.
 * 
 */
public class DoubleBox extends TextBox implements KeyPressHandler {

    /**
     * Creates an empty double box.
     */
    public DoubleBox() {
        super();
        this.addKeyPressHandler(this);
    }

    /**
     * Creates a double box that shows the given double.
     * 
     * @param d the double that has to be filled in this double box
     */
    public DoubleBox(double d) {
        setDouble(d);
    }

    /**
     * Sets the given double in this double box.
     * 
     * @param d the double that has to be filled in this double box
     */
    public void setDouble(double d) {
        if (d != 0) {
            super.setText(Double.toString(d));
        } else {
            super.setText("");
        }
    }

    /**
     * Retrieves the double that this double box contains. When this box
     * doesn't contain a double it will return 0.
     */
    public double getDouble() {
        String text = super.getText();
        double d = -1;
        try {
            d = text.equals("") ? 0 : Double.parseDouble(text);
        } catch (NumberFormatException e) {
            this.setText("" + d);
        }
        return d;
    }

    /**
     * Fills in the given text into the double box. Only strings that contain
     * strictly doubles will be processed. Other strings will be ignored with
     * the exception of the empty string.
     */
    @Override
    public void setText(String text) {
        try {
            double d = Double.parseDouble(text);
            String txt = d == 0 ? "" : text;
            super.setText(txt);
        } catch (NumberFormatException e) {
            if (text != null && text.equals("")) {
                super.setText(text);
            }
        }
    }

    /**
     * Called when KeyPressEvent is fired by this double box. Only double and
     * navigational keys are processed. Other keys are canceled.
     */
    @Override
    public void onKeyPress(KeyPressEvent event) {
        char c = event.getCharCode();

        if (!Character.isDigit(c) && c != KeyCodes.KEY_TAB && c != KeyCodes.KEY_BACKSPACE && c != KeyCodes.KEY_LEFT && c != KeyCodes.KEY_RIGHT && c != KeyCodes.KEY_DELETE && c != KeyCodes.KEY_HOME && c != KeyCodes.KEY_END && event.getSource().equals(this)) {
            this.cancelKey();
        }
    }
}
